package com.hjm.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.hjm.common.core.constants.Constants;
import com.hjm.common.core.constants.HttpConstants;
import com.hjm.common.core.utils.ThreadLocalUtils;
import com.hjm.security.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    TokenService tokenService;

    @Value("${jwt.secret}")
    private String secret;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = getToken(request);
        if(token == null) {
            return true;
        }
        tokenService.extendToken(token);
        String userKey = tokenService.getUserKey(token);

        ThreadLocalUtils.set(Constants.USER_ID,tokenService.getUserId(token));
        ThreadLocalUtils.set(Constants.USER_KEY,userKey);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        ThreadLocalUtils.remove();
    }

    private String getToken(HttpServletRequest request) {

        String token = request.getHeader(HttpConstants.AUTHENTICATION);

        if(StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)){
            token = token.replaceFirst(HttpConstants.PREFIX,"");
        }

        return token;
    }


}
